/**
 * 全站权限配置
 * 
 */
import { store } from './store'
import NProgress from 'nprogress' // progress bar

// 即时通讯模块
import { imInit, imClose } from './util/im'
import { removeAllEvent } from "./util/eventBus"



// 获取功能模块
const getModules = (to, modules) => {
  const currentModlue = modules.find(t => t.f_UrlAddress == decodeURIComponent(to.fullPath) && t.f_EnabledMark == 1)
  if (currentModlue) {
    return currentModlue;
  }
  else {
    const value = to.query.src || to.path;
    return modules.find(t => t.f_UrlAddress == value && t.f_EnabledMark == 1)
  }
}


export default {
  beforeEach: async (to, from, next) => {
    //var res = await to.matched[1].components.default();
    //console.log(to,res,'to');



    const tagWel = store.getters.tagWel

    // 获取url中的token进行设置
    // if (to.query.token) {
    //   store.dispatch("organization/user/loginToken", { token: to.query.token })
    // }

    const meta = to.meta || {}
    // console.log('111111', tagWel, to, meta.isLogin, store.state.app.system.imOpen)
    if (to.path === '/login' || meta.isLogin) {
      removeAllEvent()
      if (store.state.app.system.imOpen) {
        imClose()
      }
    }



    store.commit('SET_TAG_LOADING', true)



    if (store.getters.token) {
      let value = to.query.src || to.path//to.fullPath;

      if (meta.noLogin) {
        next()
        return;
      }

      if (store.state.app.isFirstLoad) {
        // 加载Login者信息
        await store.dispatch('organization/user/getLoginInfo')
        if (store.state.app.system.imOpen) {
          // 加载即时通讯信息
          imInit(store.getters.loginInfo.f_UserId)
        }

        // 加载菜单信息
        await store.dispatch("system/module/getList")
        // 加载动态桌面
        if (store.getters.appConfig.isDynamicHome) {
          const dynamicHomes = store.state.system.module.list.filter(t => {
            if (t.f_Target == 'desktop1' && t.f_EnabledMark == 1) {
              if (store.getters.loginInfo.f_SecurityLevel == 1) {
                return true
              }
              else {
                const moduleAuthIds = store.getters.loginInfo.moduleAuthIds || []
                if (moduleAuthIds.indexOf(t.f_ModuleId) > -1) {
                  return true
                }
              }
            }
            return false
          })

          if (dynamicHomes.length > 0) {
            // 设置Homepage
            store.commit('SET_TAG_DYNAMICHOME', dynamicHomes[0])
            dynamicHomes.forEach(t => {
              store.commit('ADD_TAG', {
                label: t.f_FullName,
                value: t.f_UrlAddress,
                params: { routerPath: "module" },
                query: {
                  close: "false",
                  name: t.f_FullName,
                  src: t.f_UrlAddress,
                  target: "desktop1"
                },
                meta: {
                  keepAlive: false
                },
              })
            })
          }
          else {
            store.commit('SET_TAG_DYNAMICHOME', undefined)
          }
        }
        store.commit('app/SET_ISFIRSTLOAD', false)
      }

      await store.dispatch("data/dbsource/clear")

      // 获取当前路由在模块中是否存在
      const modules = store.state.system.module.list
      const currentModlue = getModules(to, modules);

      // 进行路由拦截，跳转到动态桌面
      if ((value == tagWel.value || value == 'learun_desktop_nosetting') && store.getters.appConfig.isDynamicHome) {
        if (store.getters.tagDynamicHome && modules.findIndex(t => t.f_UrlAddress == store.getters.tagDynamicHome.f_UrlAddress && t.f_EnabledMark == 1) != -1) {
          window.$router.$lrRouter.goto(store.getters.tagDynamicHome)
          return
        }
        else if (value == tagWel.value) {
          store.commit('SET_TAG_DYNAMICHOME', null)
          window.$router.$lrRouter.goto({
            f_FullName: "",
            f_SortCode: 0,
            f_Target: "desktop1",
            f_UrlAddress: "learun_desktop_nosetting",
          })//在没有配置Homepage配置的情况下跳转到一个特定的默认页面
          return
        }
      }




      if (currentModlue == undefined && value != tagWel.value && !meta.isNotMenu && value != 'learun_desktop_nosetting') {
        next({ path: '/404' })
        return
      }
      // 判断当前路由是否在权限里
      const loginInfo = store.state.organization.user.loginInfo
      const moduleAuthIds = loginInfo.moduleAuthIds || []


      if (value != tagWel.value && value != 'learun_desktop_nosetting'
        && loginInfo.f_SecurityLevel != 1 && !meta.isNotMenu
        && !moduleAuthIds.includes(currentModlue.f_ModuleId)) {
        next({ path: '/403' })
        return
      }

      let label = to.query.name || meta.name || to.name
      if (currentModlue) {
        label = currentModlue.f_FullName
        value = currentModlue.f_UrlAddress
      }
      if (tagWel.value == value) {
        label = tagWel.label
      }

      if (meta.isTab !== false && !window.$validatenull(value) && !window.$validatenull(label)) {
        //console.log(to,'test');
        store.commit('ADD_TAG', {
          label: label,
          value: value,
          params: to.params,
          query: to.query,
          meta: meta,
        })
      }
      next()

    } else {
      //判断是否需要认证，没有Login访问去Login页
      if (meta.isAuth === false) {
        next()
      } else {
        next('/home')
      }
    }
  },

  afterEach: (to) => {
    NProgress.done()
    let title = to.name //store.getters.tag.label
    title = window.$router.$lrRouter.generateTitle(title)
    //根据当前的标签也获取label的值动态设置浏览器标题

    const modules = store.state.system.module.list
    let value = to.query.src || to.path//to.fullPath;
    const currentModlue = getModules(to, modules);

    const tagWel = store.getters.tagWel
    if (to.meta && to.meta.name) {
      title = to.meta.name
    }
    if (tagWel.value == value || value == 'learun_desktop_nosetting') {
      title = tagWel.label
    }
    if (currentModlue) {
      title = currentModlue.f_FullName
      value = currentModlue.f_UrlAddress
    }

    store.commit('SET_TAG_LOADING', false)

    window.$router.$lrRouter.setTitle(title)

    // 提交访问日志
    if (!to.meta.noLogin) {
      window.$api.system.log.visit({ moduleName: title, moduleUrl: value })
    }
  },

  onError: (err) => {
    //const pattern = /Loading chunk (\d)+ failed/g;
    //const isChunkLoadFailed = error.message.match(pattern);
    const targetPath = window.$router.history.pending.fullPath;
    // 因为webpack插件的bug导致打包的后的js丢失，没有太好的解决方法，目前做的是记录信息，重新打包解决
    console.error(err, targetPath)
    if (targetPath != '/404') {
      window.$router.push({ path: '/404' })
    }

  }
}


